import Vue from 'vue'
import Vuex from 'vuex'
import api from '@/api'
import addresses from '@/api/addresses'

import Member from '@/api/member'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		cartPopupVisible: false,
		shopCart: [],
		store: {},
		orderType: 'takein',
		address: {},
		addresses: addresses,
		member: Member,
		order: {}
	},
	getters: {
		isLogin: state => Object.keys(state.member).length > 0, //是否登录
		// 计算单个商品添加到购物车的数量
		goodCartNum: (state) => (id) => {
			return state.shopCart.reduce((acc, cur) => {
				if (cur.id === id) {
					return acc += cur.number
				}
				return acc
			}, 0)
		},
		// 选择商品数量气泡显示
		menuCartNum: (state) => (id) => {
			return state.shopCart.reduce((acc, cur) => {
				if (cur.cate_id === id) {
					return acc += cur.number
				}
				return acc
			}, 0)
		},
		// 计算购物车总数
		getCartGoodsNumber(state) {
			return state.shopCart.reduce((acc, cur) => acc + cur?.number, 0)
		},
		// 计算购物车总价
		getCartGoodsPrice(state) {
			return state.shopCart.reduce((acc, cur) => acc + cur?.number * cur?.price, 0)
		}
	},
	mutations: {
		SET_CART_POPUP_VISIBLE(state, visible) {
			state.cartPopupVisible = visible
		},
		SET_SHOP_CART(state, shopCart) {
			state.shopCart = shopCart
		},
		ADD_SHOP_CART(state, sIndex) {
			state.shopCart[sIndex].number += 1
		},
		REDUCE_SHOP_CART(state, sIndex) {
			if (state.shopCart[sIndex].number === 1) {
				state.shopCart.splice(sIndex, 1)
			} else {
				state.shopCart[sIndex].number -= 1
			}
			if (!state.shopCart.length) {
				state.cartPopupVisible = false
			}
		},
		REMOVE_SHOP_CART(state, shopCart) {
			state.shopCart = shopCart
			state.cartPopupVisible = false
		},
		SET_ORDER_TYPE(state, type) {
			state.orderType = type
		},
		SET_MEMBER(state, member) {
			state.member = member
		},
		SET_ADDRESS(state, address) {
			state.address = address
		},
		SET_ADDRESSES(state, addresses) {
			state.addresses = addresses
		},
		SET_STORE(state, store) {
			state.store = store
		},

		SET_ORDER(state, order) {
			state.order = order
		}
	},
	actions: {
		async getStore({
			commit
		}) {
			const store = await api('store')
			commit('SET_STORE', store)
		}
	}
})

export default store